package io.renren.utils;

import io.renren.entity.DataSource;
import org.apache.commons.lang.StringUtils;

import java.sql.*;
import java.util.Set;

/**
 * @className: DBHelper
 * @program: renren-generator
 * @description: 切换数据源的db类
 * @author: wzp12
 * @create: 2019-06-04 08:17
 **/
public class DBHelper {

    private Connection connection;

    /**
     * 获取连接
     *
     * @return
     */
    public Connection getConnection() throws SQLException, ClassNotFoundException {
        Class.forName(SettingConfig.defaultSource.getDriverClass());

        if (SettingConfig.defaultSource == null) {
            throw new RuntimeException("默认数据源为空");
        }

        connection = DriverManager.getConnection(
                SettingConfig.defaultSource.getJdbcUrl()
                , SettingConfig.defaultSource.getUser()
                , SettingConfig.defaultSource.getPassword());

        return connection;
    }

    public ResultSet query(String sql) throws SQLException, ClassNotFoundException {
        if (StringUtils.isBlank(sql)) {
            return null;
        }
        Statement statement = getConnection().createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        return resultSet;
    }


    /**
     * 关闭连接
     *
     * @throws SQLException
     */
    public void connectionClose() throws SQLException {
        connection.close();
    }

    /**
     * 测试连接
     *
     * @return
     */
    public static boolean testConnection(DataSource dataSource) throws ClassNotFoundException {
        Class.forName(dataSource.getDriverClass());

        try {
            Connection conn = DriverManager.getConnection(
                    dataSource.getJdbcUrl()
                    , dataSource.getUser()
                    , dataSource.getPassword());
            conn.close();
            return true;

        } catch (SQLException e) {
            return false;
        }
    }


}
